package cn.luckdou.WeChat.utils;

import cn.luckdou.WeChat.config.WxMpConfig;
import cn.luckdou.commons.utils.MyJsdisUtil;
import net.sf.json.JSONObject;

import java.util.Date;

public class AccessTokenUtils {
    private static Long t=1000L*60L*100L;


    public static String getToken(){
        String Access_token = (String) MyJsdisUtil.get("Access_token");
        Long Access_token_time = (Long) MyJsdisUtil.get("Access_token_time");
        if (Access_token==null || Access_token_time==null){
            return setToken();
        }
        if (new Date().getTime()-Access_token_time<=t){
            //没有过期
            return Access_token;
        }else{
            return setToken();
        }
    }

    public static String getNewToken(){
        return setToken();
    }

    private static String setToken() {
        try{
            String Access_token_json = HttpUtils.sendGet(WxMpConfig.getAccess_token_url());
            String Access_token = JSONObject.fromObject(Access_token_json).getString("access_token");
            MyJsdisUtil.set("Access_token",Access_token);
            MyJsdisUtil.set("Access_token_time",new Date().getTime());
            return Access_token;
        }catch (Exception e){
            return null;
        }
    }

}
